#include "power_board.h"
#include "ui_power_board.h"
#include "data_chart.h"
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QMessageBox>
#include <QDir>
#include <QCoreApplication>

Power_struct powerdata;

unsigned char first_write_flag = 0;   //首次写入表格标志

QString time_stamp ;
// QFile file(time_stamp);
QFile *currentFile;

// 1. 构造文件夹完整路径（这里以应用程序所在目录为例）
QString folderPath = QDir::currentPath()
                     + QDir::separator()  // 跨平台路径分隔符（/或\）
                     + "data";

Power_board::Power_board(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Power_board)
{
    // 2. 检查文件夹是否存在，不存在则创建
    QDir targetDir(folderPath);
    if (!targetDir.exists()) {
        // mkpath(".")创建当前targetDir指向的路径（支持多级目录）
        bool isCreated = targetDir.mkpath("./");
        if (!isCreated) {
            qDebug() << "文件夹创建失败！路径：" << folderPath;
            return;
        }
        qDebug() << "文件夹创建成功：" << folderPath;
    }
    time_stamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".csv";
    // 3. 构造文件完整路径
    QString filePath = folderPath
                       + QDir::separator()
                       + time_stamp;


    currentFile = new QFile(filePath);

    if (!currentFile->open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << filePath;
        return;
    }
    ui->setupUi(this);
}

Power_board::~Power_board()
{
    currentFile->close();
    delete ui;
}

//新建文件保存数据

void Power_board::on_new_file_clicked()
{

    currentFile->close();
    delete currentFile;
    currentFile = nullptr;

    // 2. 检查文件夹是否存在，不存在则创建
    QDir targetDir(folderPath);
    if (!targetDir.exists()) {
        // mkpath(".")创建当前targetDir指向的路径（支持多级目录）
        bool isCreated = targetDir.mkpath(".");
        if (!isCreated) {
            qDebug() << "文件夹创建失败！路径：" << folderPath;
            return;
        }
        qDebug() << "文件夹创建成功：" << folderPath;
    }
    time_stamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".csv";
    // 3. 构造文件完整路径
    QString filePath = folderPath
                       + QDir::separator()
                       + time_stamp;

    currentFile = new QFile(filePath);
    if (!currentFile->open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << filePath;
        return;
    }
    else{
        QMessageBox::information(this, "新建成功", filePath);
    }
}


void Power_board::show_power()
{
    ui->C_CH1->setText(QString::number(powerdata.C_CH1, 'f', 2));
    ui->C_CH2->setText(QString::number(powerdata.C_CH2, 'f', 2));
    ui->C_CH3->setText(QString::number(powerdata.C_CH3, 'f', 2));
    ui->C_CH4->setText(QString::number(powerdata.C_CH4, 'f', 2));
    // ui->C_CH5->setText(QString::number(powerdata.C_CH5, 'f', 2));
    // ui->C_CH6->setText(QString::number(powerdata.C_CH6, 'f', 2));
    // ui->C_CH7->setText(QString::number(powerdata.C_CH7, 'f', 2));
    // ui->C_CH8->setText(QString::number(powerdata.C_CH8, 'f', 2));

    ui->V_CHI->setText(QString::number(powerdata.V_CH1, 'f', 2));
    ui->V_CH2->setText(QString::number(powerdata.V_CH2, 'f', 2));
    ui->V_CH3->setText(QString::number(powerdata.V_CH3, 'f', 2));
    ui->V_CH4->setText(QString::number(powerdata.V_CH4, 'f', 2));

    ui->P_CH1->setText(QString::number((powerdata.C_CH1)*(powerdata.V_CH1), 'f', 2));
    ui->P_CH2->setText(QString::number((powerdata.C_CH2)*(powerdata.V_CH2), 'f', 2));
    ui->P_CH3->setText(QString::number((powerdata.C_CH3)*(powerdata.V_CH3), 'f', 2));
    ui->P_CH4->setText(QString::number((powerdata.C_CH4)*(powerdata.V_CH4), 'f', 2));
    // ui->P_CH5->setText(QString::number((powerdata.C_CH5)*(powerdata.V_CH1), 'f', 2));
    // ui->P_CH6->setText(QString::number((powerdata.C_CH6)*(powerdata.V_CH1), 'f', 2));
    // ui->P_CH7->setText(QString::number((powerdata.C_CH7)*(powerdata.V_CH1), 'f', 2));
    // ui->P_CH8->setText(QString::number((powerdata.C_CH8)*(powerdata.V_CH1), 'f', 2));
    this->saveToCSV();
    data_chart->data_chart();

}


void Power_board::saveToCSV() {
    time_stamp = QDateTime::currentDateTime().toString("yyyy/MM/dd/hh:mm:ss");
    QTextStream out(currentFile);
    out.setGenerateByteOrderMark(true);  // 添加 BOM 以确保 Excel 正确解析 UTF-8
    if(ui->checkBox_save->isChecked())
    {
        if(first_write_flag == 0)
        {
            // 写入表头
            out << "时间,1通道电流,2通道电流,3通道电流,4通道电流,1通道电压,2通道电压,3通道电压,4通道电压,1通道功率,2通道功率,3通道功率,4通道功率,\n";
            // 写入第一组数据
            out <<time_stamp<<","<<powerdata.C_CH1<<","<<powerdata.C_CH2<<","<<powerdata.C_CH3<<","<<powerdata.C_CH4<<","<<powerdata.V_CH1<<","<<powerdata.V_CH2<<","<<powerdata.V_CH3<<","<<powerdata.V_CH4<<","\
                <<(powerdata.C_CH1)*(powerdata.V_CH1)<<","<<(powerdata.C_CH2)*(powerdata.V_CH2)<<","<<(powerdata.C_CH3)*(powerdata.V_CH3)<<","<<(powerdata.C_CH4)*(powerdata.V_CH4)<<"\n";
            first_write_flag = 1;
        }
        else if(first_write_flag == 1)
        {
            out <<time_stamp<<","<<powerdata.C_CH1<<","<<powerdata.C_CH2<<","<<powerdata.C_CH3<<","<<powerdata.C_CH4<<","<<powerdata.V_CH1<<","<<powerdata.V_CH2<<","<<powerdata.V_CH3<<","<<powerdata.V_CH4<<","\
                <<(powerdata.C_CH1)*(powerdata.V_CH1)<<","<<(powerdata.C_CH2)*(powerdata.V_CH2)<<","<<(powerdata.C_CH3)*(powerdata.V_CH3)<<","<<(powerdata.C_CH4)*(powerdata.V_CH4)<<"\n";

        }
    }
    else
    {
        first_write_flag = 0;
    }

}

